<template>
 <div>
       <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
      <!-- 面包屑导航区域end -->

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
    <!-- 添加角色按钮end -->

      <el-table :data="roleList" border stripe max-height="600">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template  v-slot="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable  @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 === 0 ? '':'bdtop','vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable  @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18" >
                     <el-tag type="warning" 
                     v-for="item3 in item2.children" 
                     :key="item3.id" 
                     closable
                     @close="removeRightById(scope.row,item3.id)">
                        {{item3.authName}}
                     </el-tag>
                  </el-col>
                </el-row>

              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="slotProps">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(slotProps.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteRole(slotProps.row.id)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-search" @click="showSetRightDialog(slotProps.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
    <!-- 卡片视图end -->

     <!-- 添加用户对话框 -->
    <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="addDialogClosed">
        <!-- 主体区域 -->
        <el-form :model="addRoles" :rules="RoleRules" ref="addRoleRef" label-width="90px" class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addRoles.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRoles.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
    </el-dialog>
  <!-- 添加用户对话框end -->

  <!-- 修改角色对话框 -->
  <el-dialog
    title="修改角色"
    :visible.sync="editDialogVisible"
    width="30%"
    @close="editDialogClosed"
    >
   <el-form :model="editRoles" :rules="RoleRules" ref="editRoleRef" label-width="90px" class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="editRoles.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="editRoles.roleDesc"></el-input>
            </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 修改角色对话框end -->

  <!-- 分配权限对话框 -->
      <el-dialog
    title="分配权限"
    :visible.sync="setRightDialogVisible"
    width="50%"
    @close="setRightDialogClosed"
    >
    <!-- 树形事件 -->
    <el-tree :data="rightList" 
    show-checkbox node-key="id" 
    default-expand-all 
    :default-checked-keys="defKeys"
    :props="treeProps"
    ref="treeRef">
  </el-tree>

  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  <!-- 分配权限对话框 -->
 </div>


</template>

<script>
export default {
  data () {
    return {
      roleId: '', //角色id
      roleList:[], //角色列表
      setRightDialogVisible: false, // 控制分配权限对话框的显示和隐藏
      rightList: [], // 权限列表
      treeProps: { // 树形控件的熟悉绑定对象  
        children: 'children',
        label: 'authName'
      },
      defKeys:[], // 默认选中的节点id值数组
      addRoles:{
        roleName:'',
        roleDesc:''
      },
      editRoles:{},
      addDialogVisible:false,
      editDialogVisible:false,
      RoleRules:{
        roleName:[
          { required: true, message: "角色名称不能为空", trigger: "blur" },
          {min: 2,max: 10,message: "角色名称长度为2到10个字符",trigger: "blur"}
        ],
      roleDesc:[
        { min: 2, max: 15, message: "角色描述长度为2到15个字符", trigger: "blur" }
      ]
      }
    }
  },
  created(){
    this.getRoleList()
  },
  methods:{
    //获取角色列表
   async getRoleList() {
      const {data:res} = await this.$http.get('roles')
      // console.log(res);
      if(res.meta.status !==200) {
         return this.$message.error('获取角色列表失败！')
      }
      this.roleList = res.data
    },
    //重置添加角色表单
    addDialogClosed() {
      this.$refs.addRoleRef.resetFields()
    },
    //添加角色
    addRole(){
      this.$refs.addRoleRef.validate(async valid => {
        if(!valid) return
        const {data:res} = await this.$http.post('roles',this.addRoles)
        if(res.meta.status !== 201){
          return this.$message.error('创建失败')
        }
        this.$message.success(res.meta.msg)
            //隐藏添加用户框
        this.addDialogVisible = false
          //重新刷新角色列表
        this.getRoleList()
      })
    },
    //展示编辑角色对话框  
   async showEditDialog(id) {
      this.editDialogVisible = true
      const {data:res} = await this.$http.get('roles/' + id)
      if(res.meta.status !== 200 ){
        return this.$message.error('获取角色信息失败')
      }
      this.editRoles = res.data
    },
    //重置编辑角色对话框
    editDialogClosed() {
      this.$refs.editRoleRef.resetFields()
    },
    editRole() {
      this.$refs.editRoleRef.validate (async valid=> {
        if(!valid) return
        const {data:res} = await this.$http.put('roles/' + this.editRoles.roleId,{
          roleName:this.editRoles.roleName,
          roleDesc:this.editRoles.roleDesc
        })
        if(res.meta.status !== 200){
          return this.$message.error('修改角色失败')
        }
        this.$message.success('修改角色成功')
        this.editDialogVisible = false
        this.getRoleList()
      })
    },
    //删除角色
   async deleteRole(id) {
       //弹框询问用户是否删除
     const confirmRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch( err => err );
        
    if(confirmRes !== 'confirm') {
      return this.$message.info('已取消删除')
    }
    const {data:res} = await this.$http.delete('roles/' + id)
    if(res.meta.status !== 200) {
      return this.$message.error('删除失败')
    }
    this.$message.success(res.meta.msg)
    this.getRoleList()
    },
    //根据id删除对应的权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

      if(confirmResult !== 'confirm'){
        return this.$message.info('取消删除')
      }
     const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
     if(res.meta.status !== 200){
       return this.$message.error('取消权限失败！')
     }
     role.children = res.data
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const {data: res} = await this.$http.get('rights/tree')
      if(res.meta.status !== 200){
        return this.$message.error('获取权限失败！')
      }
      this.rightList  = res.data

      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true 
    },
    // 通过递归的形式，获取角色下所有的三级权限的id
    getLeafKeys(node, arr) {
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item,arr)
      });
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      // 重新赋值默认选中的节点id值数组
      this.defKeys = []
    },
    // 点击为角色分配权限
   async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
      if( res.meta.status !== 200){
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  }
}

</script>
<style scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee
}
.bdbottom{
  border-bottom: 1px solid #eee
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
